import {getRequest, myRequest, postRequest} from "../utils/MyRequest.js";
import axios from "axios";
import __ from 'lodash'
import {BASE_URL} from "../config/index.js";

export const saveSurveysApi  = async (data) => {
   const res = await postRequest("/surveys/save",data)
   return res;
}

export const getSurveysApi  = async (id) => {

   const res = await getRequest("/surveys/getDTO/" + id)
   return res;
}
/**
 * 分页查询问卷列表
 * @param page
 * @param size
 * @param query
 * @returns {Promise<AxiosResponse<any>>}
 */
export const getSurveysListApi  = (page,size,query) => {
   query = query || {};
   query = Object.keys(query).map(key => `${key}=${query[key]}`).join("&");
   return getRequest(`/surveys/page?page=${page}&size=${size}&` + query);
}
/**
 * 获取某一问卷所有提交记录
 * @param id
 */
export const getSurveysSubmitListApi  = (id) => {
   return getRequest(`/answer/list/${id}`);
}
/**
 * 获取用户页面问卷统计信息
 * @param id
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export const getUserStatisticsApi  = () => {
   return getRequest(`/surveys/user-statistics`);
}

/**
 * 获取问卷统计信息
 * @returns {Promise<axios.AxiosResponse<any>>}
 */
export const getSurveysStatisticsApi  = (id) => {
   return getRequest(`/surveys/statistics/${id}`);
}


export const getSurveysByIdApi  = (id) => {
   return getRequest(`/surveys/get/${id}`);
}
/**
 * 复制问卷
 */
export const copySurveysApi  = async (id) => {
   return await postRequest("/surveys/copy/" + id);
}
/**
 * 更新问卷配置
 */
export const updateSurveysApi  = async (data) => {
   return await postRequest("/surveys/update", data);
}

/**
 * 删除问卷
 */
export const deleteSurveysApi  = async (id) => {
   return await getRequest("/surveys/delete/" + id);
}

/**
 * 导出 答卷列表Excel
 * /surveys/statistics/file/list/{id}
 */
export const exportAnswerListExcelApi  = async (id) => {
   const response =  await axios.get(BASE_URL + "/surveys/statistics/file/list/" + id,{
      responseType: 'blob',
      transformResponse: [data => data], // 禁止自动转换
      withCredentials:true
   })
   // 解析 Content-Disposition
   const contentDisposition = response.headers['content-disposition'];
   //获取yyyy_MM_dd_HH_mm格式日期
   let date = new Date();
   let year = date.getFullYear();
   let month = date.getMonth() + 1;
   let day = date.getDate();
   let hour = date.getHours();
   let minute = date.getMinutes();
   let time = year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".xlsx";

   let fileName = '数据导出' + time; // 默认文件名

   if (contentDisposition) {
      // 尝试解析 filename*=UTF-8'' 格式
      const utf8FilenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)/);
      if (utf8FilenameMatch) {
         fileName = decodeURIComponent(utf8FilenameMatch[1]);
      } else {
         // 尝试解析 filename="..." 格式
         const filenameMatch = contentDisposition.match(/filename="(.+)"/);
         if (filenameMatch) fileName = filenameMatch[1];
      }
   }

   const url = window.URL.createObjectURL(new Blob([response.data]));
   const link = document.createElement('a');
   link.href = url;
   link.setAttribute('download', fileName);
   document.body.appendChild(link);
   link.click();
   link.remove();
}

/**
 * 导出 答卷整体比例Excel
 * /surveys/statistics/file/all/{id}
 */
export const exportAnswerAllExcelApi  = async (id) => {
   const response =  await axios.get(BASE_URL + "/surveys/statistics/file/all/" + id,{
      responseType: 'blob',
      transformResponse: [data => data], // 禁止自动转换
      withCredentials:true
   })
   // 解析 Content-Disposition
   const contentDisposition = response.headers['content-disposition'];
   //获取yyyy_MM_dd_HH_mm格式日期
   let date = new Date();
   let year = date.getFullYear();
   let month = date.getMonth() + 1;
   let day = date.getDate();
   let hour = date.getHours();
   let minute = date.getMinutes();
   let time = year + "-" + month + "-" + day + "-" + hour + "-" + minute + ".xlsx";

   let fileName = '数据导出' + time; // 默认文件名

   if (contentDisposition) {
      // 尝试解析 filename*=UTF-8'' 格式
      const utf8FilenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)/);
      if (utf8FilenameMatch) {
         fileName = decodeURIComponent(utf8FilenameMatch[1]);
      } else {
         // 尝试解析 filename="..." 格式
         const filenameMatch = contentDisposition.match(/filename="(.+)"/);
         if (filenameMatch) fileName = filenameMatch[1];
      }
   }

   const url = window.URL.createObjectURL(new Blob([response.data]));
   const link = document.createElement('a');
   link.href = url;
   link.setAttribute('download', fileName);
   document.body.appendChild(link);
   link.click();
   link.remove();
}
